package com.tensquare.articlecrawler.pipeline;
/*
 *ClassName:ArticleDbPipeline
 *Description:文章入库类，将爬取的数据存入到数据库
 *@author:可爱的大鸭子
 */

import com.tensquare.articlecrawler.dao.ArticleDao;
import com.tensquare.articlecrawler.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;
import util.IdWorker;

import java.text.SimpleDateFormat;
import java.util.Date;

@Component
public class ArticleDbPipeline implements Pipeline {
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private IdWorker idWorker;

    //设置频道id的函数
    public void setChannelId(String channelId) {
        this.channelId = channelId;
    }
    private String channelId;//频道ID

    /*ReusltItems 相当于一个Map，它保存PageProcessor处理的结果，供Pipeline使用。它的
    API与Map很类似，值得注意的是它有一个字段skip ，若设置为true，则不应被Pipeline处理。*/
    @Override
    public void process(ResultItems resultItems, Task task) {
        String title = resultItems.get("title");
        String content= resultItems.get("content");
        Article article=new Article();
        article.setId(idWorker.nextId()+"");
        article.setChannelid(channelId);
        article.setTitle(title);
        article.setContent(content);
        //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        article.setCreatetime(new Date(System.currentTimeMillis()));
        article.setState("1");
        int uid=(int)(Math.random()*8)+1;
        article.setUserid(uid+"");
        articleDao.save(article);
    }
}
